<template>
  <div class="users-base-wrapper">
    <!-- <div class="module-name">访视设计</div> -->
    <!-- <div class="module-name">
      <div>访视设计</div>
    </div> -->
    <div class="details-layout">
      <div style="overflow: hidden" v-if="!readonly">
        <el-button type="primary" style="float: left; margin-bottom: 10px" :size="size" @click="saveData">保存</el-button>
        <el-button style="float: left; margin-bottom: 10px" :size="size" @click="saveAs">另存</el-button>
        <el-button size="mini" type="default" icon="el-icon-arrow-left" @click="handleGoBack">返回上一级</el-button>
      </div>
      <div style="float: left; padding-bottom: 10px; font-size: 14px">
        <label>Casebook名称：</label>
        <el-input
          v-model.trim="dataForm.casebookName"
          size="mini"
          placeholder="请输入内容"
          style="width: 200px"
          :disabled="readonly"
          maxlength="50"
          show-word-limit
        ></el-input>
      </div>
      <div  v-if="casebookType !== 1" style="float: left; padding-bottom: 10px; padding-left: 10px">
        <label>显示条件：</label>
        <el-input
          :title="dataForm.showConditionsTxt"
          v-model="dataForm.showConditionsTxt"
          style="width: 600px"
          size="mini"
          disabled
        ></el-input>
        <el-button size="mini" style="width: 40px;margin-left: 5px;" @click="expressCondition">...</el-button>
      </div>
      <el-table
        :data="tableData.tables"
        stripe
        style="width: 100%; margin-top: 10px"
        :max-height="getTableMaxHeight()"
        :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
        :fit="true"
        :key="reftablerefresh"
        :size="size"
        v-loading="tableloading"
      >
        <el-table-column type="index" label="序号" width="100" fixed> </el-table-column>
        <el-table-column label="eCRF/Visit" width="200" prop="tableName" fixed>
          <template slot-scope="scope">
            <span>{{ scope.row.visitTableName ? scope.row.visitTableName : scope.row.tableName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :width="item.showEntry ? '240' : '120'"
          v-for="(item, visitIndex) in tableData.visits"
          :key="item.id"
          :label="item.visitName"
        >
          <div slot-scope="scope" class="flex_row">
            <el-checkbox
              ref="checkobj"
              v-model="tableData.cellResultData[scope.row.id + '&' + item.id].selected"
              :disabled="item.editType == 0 || readonly"
              @change="tableCheckedChange"
            ></el-checkbox>
            <div v-if="tableData.cellResultData[scope.row.id + '&' + item.id].selected" class="flex_row">
              <i
                :class="
                  tableData.cellResultData[scope.row.id + '&' + item.id].showTxt.length > 0
                    ? 'el-icon-finished selectOK'
                    : 'el-icon-edit-outline selectEmpty'
                "
                @click="clickShowEntry(scope.row, item.id, visitIndex)"
                :title="tableData.cellResultData[scope.row.id + '&' + item.id].showTxt"
              ></i>
              <el-input
                v-if="tableData.cellResultData[scope.row.id + '&' + item.id].showEntry"
                :title="tableData.cellResultData[scope.row.id + '&' + item.id].showTxt"
                auto-complete="off"
                size="mini"
                v-model="tableData.cellResultData[scope.row.id + '&' + item.id].showTxt"
                style="width: 120px; margin-left: 5px"
                disabled
              ></el-input>
              <el-button
                v-if="tableData.cellResultData[scope.row.id + '&' + item.id].showEntry"
                size="mini"
                style="width: 40px; margin-left: 5px"
                :disabled="item.editType == 0 || readonly"
                @click="getFormFieldSelectList(scope.$index, scope.row, $event, visitIndex, item.id)"
              >...</el-button
              >
            </div>
          </div>
        </el-table-column>
      </el-table>
      <!-- 选择字段值弹框 -->
      <el-dialog title="字段值配置" width="600px" :visible.sync="dialogvisic" :close-on-click-modal="false">
        <el-button style="float: left; margin-bottom: 10px" :size="size" type="primary" @click="doSaveSelect"
        >确认</el-button
        >
        <el-button style="float: left; margin-bottom: 10px" :size="size" @click="doClearSelect">清除</el-button>
        <el-table
          ref="multipleTable"
          tooltip-effect="dark"
          style="width: 100%;"
          :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
          :data="itemList"
          :key="refreshchick"
          v-loading="selectValueloading"
        >
          <el-table-column label="访视表" width="120" prop="tableName"> </el-table-column>
          <el-table-column label="变量" show-overflow-tooltip prop="fieldName"> </el-table-column>
          <el-table-column label="选项">
            <div slot-scope="scope">
              <el-checkbox
                v-for="item in scope.row.fieldValues"
                :key="item.fieldValue"
                v-model="scope.row.fiecheck[item.fieldValue]"
                @change="fiCheckBox(scope.row, scope.row.fiecheck, scope.$index)"
              >
                {{ item.valueName }}
              </el-checkbox>
            </div>
          </el-table-column>
        </el-table>
      </el-dialog>
      <!-- 显示条件弹出框 -->
      <el-dialog width="50%" :visible.sync="dialogexpress" :close-on-click-modal="false">
        <div style="overflow: hidden">
          <el-button style="float: left; margin-bottom: 10px" :size="size" type="primary" @click="expressSave"
          >确认</el-button
          >
          <el-button style="float: left; margin-bottom: 10px" :size="size" @click="clearShowCondition">清除</el-button>
        </div>
        <el-collapse v-for="(item, visitIndex) in displayList" :key="item.visitId">
          <el-collapse-item :name="visitIndex">
            <div slot="title" :style="item.checked ? 'color:#024182;font-weight:bolder' : 'color:#333333'">
              {{ item.visitName }}<i v-if="item.checked" style="margin-left: 10px" class="el-icon-circle-check"></i>
            </div>
            <div v-for="(val, visitTableIndex) in item.visitTables" :key="val ? val.visitTableId : visitTableIndex">
              <template v-if="val">
                <div style="color: #024182; font-weight: bolder; text-align: left; margin-top: 10px">
                  【{{ val.tableName }}】
                </div>
                <div
                  style="text-align: left; display: flex; flex-direction: row"
                  v-for="fie in val.fields"
                  :key="fie.fieldKey"
                >
                  <div style="width: 120px; text-align: right; padding-right: 10px">{{ fie.fieldName }}:</div>
                  <div style="flex-wrap: wrap; flex: 1">
                    <el-checkbox
                      v-for="(che, index) in fie.fieldValues"
                      :key="index"
                      :label="che.valueName"
                      @change="expressItem"
                      v-model="che.checked"
                    ></el-checkbox>
                  </div>
                </div>
              </template>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  data() {
    return {
      tableloading: false,
      dialogexpress: false,
      selectValueloading: false,
      reftablerefresh: 0,
      refreshchick: 0,
      type: [],
      dialogvisic: false,
      dataForm: {
        casebookName: '',
        showConditionsTxt: '',
      },
      size: 'mini',
      tableData: [],
      casebookId: '',
      itemList: [], // 表字段值待选列表
      casebookType: '1', // 1公共,2非公共
      readonly: false, // 页面是否只读的标识
      displayList: [],
      showConditions: [],
      environment: ''
    }
  },
  mounted() {
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    if (databaseInfo.isLock === '1') {
      this.readonly = true
    }
    this.edcBuildProjectId = localStorage.getItem('sys-project-id') || ''
    this.edcDataBaseId = databaseInfo.databaseId || ''
    this.dataBaseVersion = databaseInfo.databaseVersion || ''
    this.environment = sessionStorage.getItem('environment') || '0'
    this.casebookId = this.$route.query.casebookId
    this.casebookType = this.$route.query.casebookType
    this.currentTableSort = this.$route.query.sort
    // this.readonly = sessionStorage.getItem('edcDataBaseIsLock') === 1
    
    const displayList = localStorage.getItem('interview-distplay-list') && JSON.parse(localStorage.getItem('interview-distplay-list'))
    if (displayList && displayList.length > 0) {
      this.displayList = displayList
    }

    console.log('displayList', displayList)

    this.dataForm.casebookName = this.$route.query.casebookName
    this.dataForm.showConditionsTxt = ''
    this.cleanSelect()
    this.findPage()
    window.addEventListener('resize', () => {
      this.getTableMaxHeight()
      this.$forceUpdate()
    })
  },
  methods: {
    ...mapActions('visitDesign', [
      'nowCasebookConfig',
      'visitCasebookShowConditions',
      'visitSaveOrUpdate',
      'getTableField'
    ]),
    // 表格自适应屏幕高度
    getTableMaxHeight() {
      return document.documentElement.clientHeight - 200
    },

    // 返回上一级目录
    handleGoBack() {
      localStorage.removeItem('interview-distplay-list')
      this.$router.go(-1)
    },

    cleanSelect () {
      if (this.displayList != null) {
        for (const dis of this.displayList) {
          if (dis) {
            dis.checked = false
            if (dis.visitTables) {
              for (const vis of dis.visitTables) {
                if (vis && vis.fields) {
                  for (const fie of vis.fields) {
                    if (fie && fie.fieldValues) {
                      for (const fieval of fie.fieldValues) {
                        fieval.checked = false
                      }
                    }
                  }
                }
              }
            }
          }
        }
      } else {
        this.displayList = []
      }
    },

    // 显示条件弹出框
    expressCondition() {
      this.dialogexpress = true
    },
    // 显示条件弹出框确认按钮
    expressSave() {
      this.dialogexpress = false
      const showConditions = []
      const Module = []
      for (const item of this.dieate) {
        if (item && item.visitTables) {
          for (const itemON of item.visitTables) {
            if (itemON && itemON.fields) {
              for (const itemTw of itemON.fields) {
                if (itemTw && itemTw.fieldValues) {
                  for (const iteThr of itemTw.fieldValues) {
                    if (iteThr.checked === true) {
                      showConditions.push({
                        visitId: item.visitId,
                        visitTableId: itemON.visitTableId,
                        tableField: itemTw.fieldKey,
                        fieldValue: iteThr.fieldValue,
                      })
                      Module.push(
                        item.visitName + ':' + itemON.tableName + ':' + itemTw.fieldName + ':' + iteThr.valueName
                      )
                    }
                  }
                }
              }
            }
          }
        }
      }
      this.dataForm.showConditionsTxt = Module.join('|')
      this.showConditions = showConditions
    },
    // 多选选项
    expressItem() {
      this.dieate = []
      for (const item of this.displayList) {
        let thisItemSelected = false
        if (item) {
          item.checked = false
          if (item.visitTables) {
            for (const itemTw of item.visitTables) {
              if (itemTw && itemTw.fields) {
                for (const itemThr of itemTw.fields) {
                  if (itemThr && itemThr.fieldValues) {
                    for (const che of itemThr.fieldValues) {
                      if (che && che.checked) {
                        thisItemSelected = true
                        item.checked = true
                      }
                    }
                  }
                }
              }
            }
          }
        }
        if (thisItemSelected) {
          this.dieate.push(item)
        }
      }
      this.$forceUpdate()
    },
    // 显示选择表单字段值的弹框
    getFormFieldSelectList (index, datas, event, visitIndex, visitId) {
      // 获取该访视列已经勾选表单的ids
      const selectVisitIds = []
      for (const key in this.tableData.cellResultData) {
        const cell = this.tableData.cellResultData[key]
        if (cell.selected && cell.visitId === visitId) {
          selectVisitIds.push(cell.visitTableId)
        }
      }
      this.dialogvisic = true
      this.currentClickFormID = datas.id // 当前点击所在的访视id
      this.currentClickVisitID = visitId // 当前点击所在的表单id
      const data = {
        databaseId: this.edcDataBaseId,
        databaseCrfId: datas.databaseCrfId,
        ids: selectVisitIds,
        projectId: this.edcBuildProjectId,
        databaseVersion: this.dataBaseVersion,
        environment: this.environment
      }
      this.selectValueloading = true
      // 根据表单ids获取单选的数据
      this.getTableField({ data })
        .then(res => {
          if (res.code === 200) {
            this.itemList = res.data
            for (let index = 0; index < this.itemList.length; index++) {
              const item = this.itemList[index]
              item.fiecheck = {}
              // 之前已选的条目值勾选
              const curCellData = this.tableData.cellResultData[datas.id + '&' + visitId]
              if (curCellData != null && curCellData.itemValueEntrys != null) {
                for (const table of curCellData.itemValueEntrys) {
                  if (
                    table.fieldValues != null &&
                    item.visitTableId === table.visitTableId &&
                    item.fieldKey === table.tableField
                  ) {
                    const selectValIds = table.fieldValues.split(',')
                    for (const valueId of selectValIds) {
                      item.fiecheck[valueId] = true // 勾选已有值
                    }
                  }
                }
              }
              // 勾选的值数据组装
              this.fiCheckBox(item, item.fiecheck, index)
            }
          }
          this.selectValueloading = false
        })
        .catch(error => {
          this.selectValueloading = false
          this.$message.error(error)
        })
    },
    /**
     * 字段值勾选事件
     * @param {行数据} data
     * @param {勾选的id数据} selectIdsObj
     * @param {行标} rowIndex
     */
    fiCheckBox(data, selectIdsObj, rowIndex) {
      this.refreshchick++
      const optSelectIdArr = [] // 勾选的字段值id
      const optSelectNameArr = [] // 勾选的字段值名称
      if (data && data.fieldValues) {
        for (const opt of data.fieldValues) {
          if (selectIdsObj) {
            for (const id in selectIdsObj) {
              if (id === opt.fieldValue && selectIdsObj[id] === true) {
                optSelectNameArr.push(opt.valueName)
                optSelectIdArr.push(id)
              }
            }
          }
        }
      }
      // 勾选的记录设置到原列表
      if (optSelectNameArr.length > 0) {
        this.itemList[rowIndex].showValueTxt = data.tableName + ':' + data.fieldName + ':' + optSelectNameArr.join(',')
        this.itemList[rowIndex].selectValueIds = optSelectIdArr.join(',') // 每行记录已勾选的值
      } else {
        // 都没选的设置为空
        this.itemList[rowIndex].showValueTxt = ''
        this.itemList[rowIndex].selectValueIds = ''
      }
    },
    /**
     * 选自字段值弹框 最终确认
     */
    doSaveSelect() {
      this.dialogvisic = false
      const itemValueCnArr = [] // 所有选择的字段值
      const itemValueEntrys = [] // 所有选择的涉及条目
      for (const item of this.itemList) {
        if (item.selectValueIds != null && item.selectValueIds.length > 0) {
          itemValueCnArr.push(item.showValueTxt)
          // 提前组装接口需要的entry结构
          itemValueEntrys.push({
            visitTableId: item.visitTableId,
            tableField: item.fieldKey,
            fieldValues: item.selectValueIds,
          })
        }
      }
      const cell = this.tableData.cellResultData[this.currentClickFormID + '&' + this.currentClickVisitID]
      cell.showTxt = itemValueCnArr.join('|')
      cell.itemValueEntrys = itemValueEntrys
      // this.reftablerefresh++
    },
    // 清空字段值选择
    doClearSelect() {
      for (const item of this.itemList) {
        item.fiecheck = {}
        item.selectValueIds = ''
      }
      this.refreshchick++
    },

    // 另存
    saveAs() {
      this.casebookId = null
      this.saveData()
    },
    /**
     * 保存配置按钮
     */
    saveData() {
      if (this.dataForm.casebookName == null || this.dataForm.casebookName.length === 0) {
        this.$message({
          type: 'warning',
          message: '请填写Casebook名称!',
        })
        return
      }
      const casebook = []
      for (const key in this.tableData.cellResultData) {
        const cell = this.tableData.cellResultData[key]
        if (cell.selected && cell.editType === 1) {
          casebook.push({
            visitId: cell.visitId,
            visitTableId: cell.visitTableId,
            entrys: cell.itemValueEntrys,
          })
        }
      }
      const data = {
        id: this.casebookId,
        databaseId: this.edcDataBaseId,
        casebookName: this.dataForm.casebookName,
        casebookType: this.casebookType,
        casebookTables: casebook,
        showConditions: this.showConditions,
        projectId: this.edcBuildProjectId,
        databaseVersion: this.dataBaseVersion,
        environment: this.environment,
        sort: this.currentTableSort || 0
      }
      if (this.casebookId == null) {
        this.visitSaveOrUpdate({ data })
          .then(resp => {
            if (resp.code === 200) {
              this.findPage()
              this.dialogVisible = false
              this.editDialog = false
              this.dataForm.casebookName = ''
              localStorage.removeItem('interview-distplay-list')
              this.goback()
              this.$message({
                type: 'success',
                message: '添加成功',
              })
            }
          })
      } else {
        // 编辑
        this.visitSaveOrUpdate({ data })
          .then(resp => {
            if (resp.code === 200) {
              this.$message({
                type: 'success',
                message: '编辑成功',
              })
              this.findPage()
              this.dialogVisible = false
              this.editDialog = false
              this.dataForm.casebookName = ''
              localStorage.removeItem('interview-distplay-list')
              this.goback()
              
            }
          })
          
      }
    },
    // 返回访视设计页面
    goback() {
      this.$router.push({
        path: '/visitDesign',
        query: {
          activeName: 'third',
        }
      })
    },
    // 获取数据
    findPage: function () {
      this.tableloading = true
      const params = {
        databaseId: this.edcDataBaseId,
        casebookId: this.casebookId,
        projectId: this.edcBuildProjectId,
        databaseVersion: this.dataBaseVersion,
        environment: this.environment
      }
      this.nowCasebookConfig({ params })
        .then(res => {
          if (res.code === 200 && res.data != null) {
            const tableData = res.data
            this.dataForm.casebookName = tableData.casebookName
            this.casebookType = tableData.casebookType
            this.showConditions = tableData.usedCondition
            if (tableData.visits) {
              for (const visit of tableData.visits) {
                visit.showEntry = false
              }
            }
            tableData.cellResultData = {}
            // 勾选记录处理
            for (const lineData of tableData.tables) {
              for (const visit of tableData.visits) {
                // 每个单元格对象
                const cellObj = {
                  visitTableId: lineData.id, // 行-表单id
                  visitId: visit.id, // 列 - 访视id
                  showTxt: '', // 选择的条件文字
                  selected: false, // 勾选状态
                  editType: visit.editType, // 是否可编辑1是2否
                  showEntry: false,
                }
                // 组装已选择的表单字段和值【表名称:字段名称:值名称 | 表名称:字段名称:值名称】
                for (const item of tableData.visitCasebookTables) {
                  const defValueCnArr = []
                  const itemValueEntrys = []
                  // && item.hasEbtry === 1 
                  if (item && item.usedEntrys.length > 0) {
                    // 有设置显示控制
                    for (const entry of item.usedEntrys) {
                      const valNames = []
                      const valIds = []
                      for (const one of entry.valueList) {
                        valNames.push(one.valueName)
                        valIds.push(one.fieldValue)
                      }
                      const combinStr = entry.visitTableName + ':' + entry.tableFieldName + ':' + valNames.join(',')
                      defValueCnArr.push(combinStr)
                      // 涉及条目组装
                      itemValueEntrys.push({
                        visitTableId: entry.visitTableId,
                        tableField: entry.tableField,
                        fieldValues: valIds.join(','),
                        valNames: combinStr,
                      })
                    }
                  }
                  // 有勾选记录则组装
                  if (lineData.id === item.visitTableId && item.visitId === visit.id) {
                    cellObj.showTxt = defValueCnArr.join('|')
                    cellObj.selected = true
                    cellObj.showEntry = false
                    // 组装涉及条目,编辑时需要带上之前已选数据
                    cellObj.itemValueEntrys = itemValueEntrys
                  }
                }
                tableData.cellResultData[cellObj.visitTableId + '&' + cellObj.visitId] = cellObj
              }
            }
            // 显示条件组装
            const list = []
            if (tableData.usedCondition) {
              for (const element of tableData.usedCondition) {
                for (const item of this.displayList) {
                  if (item && element.visitId === item.visitId) {
                    for (const row of item.visitTables) {
                      if (row && element.visitTableId === row.visitTableId) {
                        for (const fie of row.fields) {
                          if (fie && element.tableField === fie.fieldKey) {
                            for (const fieval of fie.fieldValues) {
                              if (fieval && element.fieldValue === fieval.fieldValue) {
                                list.push(
                                  item.visitName + ':' + row.tableName + ':' + fie.fieldName + ':' + fieval.valueName
                                )
                                fieval.checked = true
                                item.checked = true
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
            this.dataForm.showConditionsTxt = list.join('|')
           
            this.tableData = tableData
            this.$forceUpdate()
          }
          this.tableloading = false
        })
        .catch(error => {
          this.tableloading = false
          this.$message.error(error)
        })
    },

    /**
     * 勾选事件
     */
    tableCheckedChange() {
      // this.reftablerefresh++
    },

    /**
     * 清空casebook显示条件
     */
    clearShowCondition() {
      for (const item of this.displayList) {
        if (item) {
          item.checked = false
          if (item.visitTables) {
            for (const itemTw of item.visitTables) {
              if (itemTw && itemTw.fields) {
                for (const itemThr of itemTw.fields) {
                  if (itemThr && itemThr.fieldValues) {
                    for (const che of itemThr.fieldValues) {
                      che.checked = false
                    }
                  }
                }
              }
            }
          }
        }
      }
      this.$forceUpdate()
    },
    // 展示显示条件
    clickShowEntry(row, itemId, visitIndex) {
      this.tableData.cellResultData[row.id + '&' + itemId].showEntry =
        !this.tableData.cellResultData[row.id + '&' + itemId].showEntry
      let hasShowEntry = false
      for (const table of this.tableData.tables) {
        if (this.tableData.cellResultData[table.id + '&' + itemId].showEntry) {
          hasShowEntry = true
          break
        }
      }
      this.tableData.visits[visitIndex].showEntry = hasShowEntry
      // this.reftablerefresh++
    },
  },
}
</script>

<style lang="scss" scoped>
.users-base-wrapper {
  display: flex;
  flex-direction: column;
  .module-name {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 40px;
    padding-left: 24px;
    font-family: 'PingFang SC';
    font-size: 16px;
    font-weight: 500;
    background-color: $white;
    box-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  }


  .details-layout {
    height: calc(100vh - 130px);
    padding: 10px 20px 0 20px;

    background-color: #fff;
  }
}
.visitName {
  background-color: #fff;
  padding: 5px;
  height: 100%;
}

.flex_row {
  display: flex;
  flex-direction: row;
}

.selectOK {
  color: #40ae12;
  font-size: 16px;
  margin-top: 5px;
  margin-left: 5px;
}

.selectEmpty {
  color: #fecf20;
  font-size: 16px;
  margin-top: 5px;
  margin-left: 5px;
}
</style>
